<?php
include_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'nl_common.func.php';
class nl_asset_item {
	static public $order=array(
		NL_ORDER_NUM_ASC=>" order by asset.nns_order asc",
		NL_ORDER_NUM_DESC=>" order by asset.nns_order desc",
		NL_ORDER_TIME_ASC=>" order by asset.nns_create_time asc",
		NL_ORDER_TIME_DESC=>" order by asset.nns_create_time desc",
		NL_ORDER_CLICK_ASC=>" order by asset.nns_play_count asc",
		NL_ORDER_CLICK_DESC=>" order by asset.nns_play_count desc",
	);
	const CACHE_TIME_OUT=300;
		/**
	 * 从DC模块获取媒资包栏目及所属子栏目的内容列表信息数
	 * @param dc DC模块
	 * @param String 媒资包ID
	 * @param String 媒资包栏目ID
	 * @param String EPG输出标识
	 * @param int 起始查询记录位置
	 * @param int 查询记录条数
	 * @param String 读取策略 NL_DC_AUTO| NL_DC_DB | NL_DC_CACHE
	 * @return *
	 * 			Array 媒资包栏目及所属子栏目的内容列表信息结果
	 * 			FALSE 查询失败
	 * 			TRUE  查询成功，但无数据
	 */
	static public function count_asset_item_list_by_child($dc,$asset_id,$category_id,$tag,$if_include_child=true,$except_category=null,$policy=NL_DC_AUTO){
		$result = null;
		if ($policy == NL_DC_AUTO){
			if ($dc->is_cache_enabled()) {
				$result = self::_count_asset_item_list_by_child_cache($dc->cache(),$asset_id,$category_id,$tag,$if_include_child,$except_category);
				if ($result === FALSE ) {
					$result = self::_count_asset_item_list_by_child_db($dc->db(),$asset_id,$category_id,$tag,$if_include_child,$except_category);
					self::_set_count_asset_item_list_by_child_cache($dc->cache(),$asset_id,$category_id,$tag,$if_include_child,$except_category,$result);
				}
			}
			else {
				$result = self::_count_asset_item_list_by_child_db($dc->db(),$asset_id,$category_id,$tag,$if_include_child,$except_category);
			}
		}elseif($policy == NL_DC_DB){
			$result = self::_count_asset_item_list_by_child_db($dc->db(),$asset_id,$category_id,$tag,$if_include_child,$except_category);
		}elseif($policy == NL_DC_CACHE){
			$result = self::_count_asset_item_list_by_child_cache($dc->cache(),$asset_id,$category_id,$tag,$if_include_child,$except_category);
		}

		return $result;
//		return self::_count_asset_item_list_by_child_db($dc->db(),$asset_id,$category_id,$tag,$if_include_child,$except_category);
	}
	
	static public function _count_asset_item_list_by_child_cache($cache,$asset_id,$category_id,$tag,$if_include_child,$except_category){
		if ($cache===NULL) return FALSE;
		$category_id=empty($category_id)?'1000':$category_id;
//		获取GUID标识
		$comp_key=$cache->get('index_asset|#'.$asset_id);

		return unserialize($cache->get($comp_key.'|#'.$category_id.'|#'.$tag.'|#'.$if_include_child.'|#'.$except_category.'|#count'));
	}
	
	static public function _set_count_asset_item_list_by_child_cache($cache,$asset_id,$category_id,$tag,$if_include_child,$except_category,$data){
		if ($cache===NULL) return FALSE;
		$category_id=empty($category_id)?'1000':$category_id;
		$comp_key=$cache->get('index_asset|#'.$asset_id);
		$comp_key=($comp_key===FALSE)?np_guid_rand():$comp_key;
		$cache->set('index_asset|#'.$asset_id,$comp_key);
		return $cache->set($comp_key.'|#'.$category_id.'|#'.$tag.'|#'.$if_include_child.'|#'.$except_category.'|#count',serialize($data),self::CACHE_TIME_OUT);
	}
	

	static private function _count_asset_item_list_by_child_db($db,$asset_id,$category_id,$tag,$if_include_child=true,$except_category=null) {
		$category_id=empty($category_id)?'1000':$category_id;


        if($if_include_child && $except_category){
        	$except_sql = ' 1 and ';
        	if ($except_category){
        		$except_sql=' not ( ';
        		$except_arr=explode('||',$except_category);
        		foreach ($except_arr as $except_item){
        			$except_item=explode('|',$except_item);
        			$except_sql.= " nns_category_id like '".$except_item[1]."%' or";
        		}
        		$except_sql=rtrim($except_sql,'or');
        		$except_sql.=') and ';
        	}
        	
        	
			$sql = ' select count(*) as num from nns_assists_item where ' .
					'nns_assist_id=\''.$asset_id.'\' and ' .
					'nns_category_id like \''.$category_id.'%\' and ' .
					$except_sql.
					'(nns_tag=\'\' or ' .
					'ISNULL(nns_tag) or ' .
					'LOCATE(\','.$tag.',\',CONCAT(\',\',nns_tag))>0) and ' .
					'(nns_single_tag=\'\' or ' .
					'ISNULL(nns_single_tag) or ' .
					'LOCATE(\','.$tag.',\',CONCAT(\',\',nns_single_tag))>0) '.$except_category;
        }else{
 			$sql = ' select count(*) as num from nns_assists_item where ' .
					'nns_assist_id=\''.$asset_id.'\' and ' .
					'nns_category_id=\''.$category_id.'\' and ' .
					'(nns_tag=\'\' or ' .
					'ISNULL(nns_tag) or ' .
					'LOCATE(\','.$tag.',\',CONCAT(\',\',nns_tag))>0) and ' .
					'(nns_single_tag=\'\' or ' .
					'ISNULL(nns_single_tag) or ' .
					'LOCATE(\','.$tag.',\',CONCAT(\',\',nns_single_tag))>0)';
        }
//		echo $sql;
//		die;
		$result=nl_query_by_db($sql, $db);
		return $result[0]['num'];
	}
		/**
	 * 从DC模块获取媒资包栏目及所属子栏目的内容列表信息
	 * @param dc DC模块
	 * @param String 媒资包ID
	 * @param String 媒资包栏目ID
	 * @param String EPG输出标识
	 * @param int 起始查询记录位置
	 * @param int 查询记录条数
	 * @param String 读取策略 NL_DC_AUTO| NL_DC_DB | NL_DC_CACHE
	 * @return *
	 * 			Array 媒资包栏目及所属子栏目的内容列表信息结果
	 * 			FALSE 查询失败
	 * 			TRUE  查询成功，但无数据
	 * yxt:2013年1月16日20:25:12，在最后增加了一个参数，判断是否需要获取子栏目的内容，true/1包含，false/0不包含
	 */
	static public function get_asset_item_list_by_child($dc,$asset_id,$category_id,$tag,$since=0,$num=10,$order=NL_ORDER_NUM_DESC,$policy=NL_DC_AUTO,$if_include_child=true,$except_category=null) {
		$result = null;
		if ($policy == NL_DC_AUTO){
			if ($dc->is_cache_enabled()) {
				$result = self::_get_asset_item_list_by_child_cache($dc->cache(),$asset_id,$category_id,$tag,$since,$num,$order,$if_include_child,$except_category);
				if ($result === FALSE ) {
					$result = self::_get_asset_item_list_by_child_db($dc->db(),$asset_id,$category_id,$tag,$since,$num,$order,$if_include_child,$except_category);
					self::_set_asset_item_list_by_child_cache($dc->cache(),$asset_id,$category_id,$tag,$since,$num,$order,$result,$if_include_child,$except_category);
				}
			}
			else {
				$result = self::_get_asset_item_list_by_child_db($dc->db(),$asset_id,$category_id,$tag,$since,$num,$order,$if_include_child,$except_category);
			}
		}elseif($policy == NL_DC_DB){
			$result = self::_get_asset_item_list_by_child_db($dc->db(),$asset_id,$category_id,$tag,$since,$num,$order,$if_include_child,$except_category);
		}elseif($policy == NL_DC_CACHE){
			$result = self::_get_asset_item_list_by_child_cache($dc->cache(),$asset_id,$category_id,$tag,$since,$num,$order,$if_include_child,$except_category);
		}

		return $result;
	}
	/**
	 * 获取所有的媒资包id
	 * @param unknown_type $dc
	 */
	static public function get_asset_item_all($dc){
		$sql="select nns_id from  nns_assists";
		return nl_query_by_db($sql, $dc->db());
	}

	static private function _get_asset_item_list_by_child_db($db,$asset_id,$category_id,$tag,$since,$num,$order,$if_include_child=true,$except_category=null) {
		$category_id=empty($category_id)?'1000':$category_id;
		$order_str='';

		switch ($order){
			case NL_ORDER_NUM_DESC:
				$order_str=' nns_order desc ';
			break;
			case NL_ORDER_NUM_ASC:
				$order_str=' nns_order asc ';
			break;
			case NL_ORDER_TIME_DESC:
				$order_str=' nns_create_time desc ';
			break;
			case NL_ORDER_TIME_ASC:
				$order_str=' nns_create_time asc ';
			break;
			case NL_ORDER_CLICK_DESC:
				$order_str=' nns_play_count desc ';
			break;
			case NL_ORDER_CLICK_ASC:
				$order_str=' nns_play_count asc ';
			break;
			default:
				$order_str=' nns_order desc ';
			break;
		}
			if($if_include_child){
        		$except_sql = ' 1 and ';
			if ($except_category){
				
        		$except_sql=' not ( ';
        		$except_arr=explode('||',$except_category);
        		foreach ($except_arr as $except_item){
        			$except_item=explode('|',$except_item);
        			$except_sql.= " nns_category_id like '".$except_item[1]."%' or";
        		}
        		$except_sql=rtrim($except_sql,'or');
        		$except_sql.=') and ';
        	}
				
				
			$sql = ' select * from nns_assists_item where ' .
					'nns_assist_id=\''.$asset_id.'\' and ' .
					'nns_category_id like \''.$category_id.'%\' and ' .
					$except_sql.
					'(nns_tag=\'\' or ' .
					'ISNULL(nns_tag) or ' .
					'LOCATE(\','.$tag.',\',CONCAT(\',\',nns_tag))>0) and ' .
					'(nns_single_tag=\'\' or ' .
					'ISNULL(nns_single_tag) or ' .
					'LOCATE(\','.$tag.',\',CONCAT(\',\',nns_single_tag))>0) order by ' .
					$order_str .
					'limit '.$since.','.$num;
			}else{
				$sql = ' select * from nns_assists_item where ' .
					'nns_assist_id=\''.$asset_id.'\' and ' .
					'nns_category_id=\''.$category_id.'\' and ' .
					'(nns_tag=\'\' or ' .
					'ISNULL(nns_tag) or ' .
					'LOCATE(\','.$tag.',\',CONCAT(\',\',nns_tag))>0) and ' .
					'(nns_single_tag=\'\' or ' .
					'ISNULL(nns_single_tag) or ' .
					'LOCATE(\','.$tag.',\',CONCAT(\',\',nns_single_tag))>0) order by ' .
					$order_str .
					'limit '.$since.','.$num;
			}
//		echo $sql;
//		die;
		return nl_query_by_db($sql, $db);
	}

	static private function _get_asset_item_list_by_child_cache($cache,$asset_id,$category_id,$tag,$since,$num,$order,$if_include_child,$except_category) {
		if ($cache===NULL) return FALSE;
		$category_id=empty($category_id)?'1000':$category_id;
//		获取GUID标识
		$comp_key=$cache->get('index_asset|#'.$asset_id);

		return unserialize($cache->get($comp_key.'|#'.$category_id.'|#'.$tag.'|#'.$since.'|#'.$num.'|#'.$order.'|#'.$if_include_child.'|#'.$except_category));
	}

	static private function _set_asset_item_list_by_child_cache($cache,$asset_id,$category_id,$tag,$since,$num,$order,$data,$if_include_child,$except_category) {
		if ($cache===NULL) return FALSE;
		$category_id=empty($category_id)?'1000':$category_id;
		$comp_key=$cache->get('index_asset|#'.$asset_id);
		$comp_key=($comp_key===FALSE)?np_guid_rand():$comp_key;
		$cache->set('index_asset|#'.$asset_id,$comp_key);
		return $cache->set($comp_key.'|#'.$category_id.'|#'.$tag.'|#'.$since.'|#'.$num.'|#'.$order.'|#'.$if_include_child.'|#'.$except_category,serialize($data),self::CACHE_TIME_OUT);
	}
//	对于包含子目录的栏目查询 只能删除该包下所有内容缓冲
	static public function delete_asset_item_list_by_child_cache($dc,$asset_id) {
		if ($dc->cache()===NULL) return FALSE;
		$category_id=empty($category_id)?'1000':$category_id;
		return $dc->cache()->delete('index_asset|#'.$asset_id);
	}
	static public function set_media_assets_item_score($dc,$nns_media_assets_item_id,$socre){
		$media_assets_item_info = self::get_media_assets_item_info($dc,$nns_media_assets_item_id);

        $video_id = $media_assets_item_info['nns_video_id'];

		$sql = "update nns_assists_item set nns_score=IFNULL(nns_score,0)+$socre , nns_score_count=IFNULL(nns_score_count,0)+1 where nns_video_id='$video_id'";

		return nl_execute_by_db($sql,$dc->db());
	}
	
	static public function set_video_item_score($dc,$video_id,$video_type,$socre){

		$sql = "update nns_assists_item set nns_score=IFNULL(nns_score,0)+$socre , nns_score_count=IFNULL(nns_score_count,0)+1 where nns_video_id='$video_id'";

		return nl_execute_by_db($sql,$dc->db());
	}
	
	static public function get_media_assets_item_info($dc,$nns_media_assets_item_id,$policy=NL_DC_AUTO)
	{
		return self::get_media_assets_item_info_by_db($dc->db(),$nns_media_assets_item_id);
	}
	static public function get_media_assets_item_info_by_db($db,$nns_media_assets_item_id){
		$sql = "select * from nns_assists_item where nns_id='$nns_media_assets_item_id'";
		return nl_db_get_one($sql, $db);
	}
	static public function epg_get_asset_item_search($dc,$tag,$asset_id,$category_id,$since=0,$num=10,$order=NL_ORDER_NUM_ASC,$include_child_category=1,$type="pinyin_firstchar",$search=null,$video_type=null,$except_category=null){
//		当媒资包ID为数组时,应该为查询数组内媒资 BY S67 2013-03-22
		if (!is_array($asset_id) && !empty($asset_id)){
			$asset_sql=" asset.nns_assist_id='{$asset_id}' ";
		}elseif (is_array($asset_id)){
			$asset_sql_request='';
			$asset_sql=' asset.nns_assist_id in ( ';
			foreach ($asset_id as $item_id){
				$asset_sql_request.=" '{$item_id}',";
			}
			$asset_sql_request=rtrim($asset_sql_request,',');
			$asset_sql.=$asset_sql_request.') ';
			
			$child_category='1000';
		}else{
			$asset_sql=' 1=1 ';
			$child_category='';
		}
		
		
		if ($include_child_category && $except_category){
        		$except_sql=' and not ( ';
        		$except_arr=explode('||',$except_category);
        		foreach ($except_arr as $except_item){
        			$except_item=explode('|',$except_item);
        			$except_sql.= " (asset.nns_category_id like '".$except_item[1]."%' and ";
        			$except_sql.=" asset.nns_assist_id='".$except_item[0]."') or";
        		}
        		$except_sql=rtrim($except_sql,'or');
        		$except_sql.=') ';
        	}
		
		//0不包含子栏目1包含子栏目
		if(!empty($category_id)){
			if($include_child_category==0){
				$child_category="and asset.nns_category_id='{$category_id}'";
			}else{
				$child_category="and asset.nns_category_id like '{$category_id}%'";
			}
		}
		
		//组装LIMIT
		if(empty($since)&&$since!=0){
			$limit="";
		}elseif(empty($num)){
			$limit="LIMIE $since";
		}else{
			$limit="LIMIT {$since},{$num}";
		}
		$where_like='';
		if (!empty($search)){
			$types=explode('|',$type);
			$where_like=" and (";
			foreach ($types as $type_value){
		    	switch ($type_value){
		    		case "name_firstchar": $where_like.="  asset.nns_video_name like '{$search}%'";break;
		    		case "name_likechar": $where_like.="  asset.nns_video_name like '%{$search}%'";break;
		//    		case "pinyin_firstchar": $where_like.="  asset.nns_pinyin like '{$search}%'";break;
		    		case "pinyin_likechar": $where_like.="  asset.nns_pinyin like '%{$search}%'";break;
		    		case "en_firstchar": $where_like.="  asset.nns_english_index like '{$search}%'";break;
		    		case "en_likechar": $where_like.="  asset.nns_english_index like '%{$search}%'";break;
		    		default: $where_like.=" asset.nns_pinyin like '{$search}%'";break;
		    	}
		    	
		    	$where_like .=' or';
			}
			$where_like=rtrim ($where_like,'or');
			$where_like.=") ";
		}
		
		$where_type = '';
		if($video_type!==NULL && $video_type!==''){
			$where_type = "and asset.nns_video_type='{$video_type}' ";
		}
		
		$order=self::$order[$order];
		$where_tag = '';
		if($tag!==NULL && $tag!==''){
			$where_tag = "and ((LOCATE(',{$tag},',CONCAT(',',asset.nns_tag)))>0 or asset.nns_tag='' or ISNULL(asset.nns_tag))";
		}
		
		$sql="select asset.* from nns_assists_item as asset where {$asset_sql} {$child_category} {$where_tag} {$where_like} {$where_type} {$except_sql} {$order} {$limit}";
//    	echo $sql;die;
    	return nl_query_by_db($sql, $dc->db());
	}	
	static public function count_asset_item_search($dc,$tag,$asset_id,$category_id,$include_child_category=1,$type="pinyin_firstchar",$search=null,$video_type=null,$except_category=null){
//		当媒资包ID为数组时,应该为查询数组内媒资 BY S67 2013-03-22
		if (!is_array($asset_id) && !empty($asset_id)){
			$asset_sql=" asset.nns_assist_id='{$asset_id}' ";
		}elseif (is_array($asset_id)){
			$asset_sql_request='';
			$asset_sql=' asset.nns_assist_id in ( ';
			foreach ($asset_id as $item_id){
				$asset_sql_request.=" '{$item_id}',";
			}
			$asset_sql_request=rtrim($asset_sql_request,',');
			$asset_sql.=$asset_sql_request.') ';
			
			$child_category='1000';
		}else{
			$asset_sql=' 1=1 ';
			$child_category='';
		}
		
		
		
		if ($include_child_category && $except_category){
        		$except_sql=' and not ( ';
        		$except_arr=explode('||',$except_category);
        		foreach ($except_arr as $except_item){
        			$except_item=explode('|',$except_item);
        			$except_sql.= " (asset.nns_category_id like '".$except_item[1]."%' and ";
        			$except_sql.=" asset.nns_assist_id='".$except_item[0]."') or";
        		}
        		$except_sql=rtrim($except_sql,'or');
        		$except_sql.=') ';
        	}
		
		//0不包含子栏目1包含子栏目
		if(!empty($category_id)){
			if($include_child_category==0){
				$child_category="and asset.nns_category_id='{$category_id}'";
			}else{
				$child_category="and asset.nns_category_id like '{$category_id}%'";
			}
		}
		
		$where_like='';
		if (!empty($search)){
			$types=explode('|',$type);
			$where_like=" and (";
			foreach ($types as $type_value){
		    	switch ($type_value){
		    		case "name_firstchar": $where_like.="  asset.nns_video_name like '{$search}%'";break;
		    		case "name_likechar": $where_like.="  asset.nns_video_name like '%{$search}%'";break;
		//    		case "pinyin_firstchar": $where_like.="  asset.nns_pinyin like '{$search}%'";break;
		    		case "pinyin_likechar": $where_like.="  asset.nns_pinyin like '%{$search}%'";break;
		    		case "en_firstchar": $where_like.="  asset.nns_english_index like '{$search}%'";break;
		    		case "en_likechar": $where_like.="  asset.nns_english_index like '%{$search}%'";break;
		    		default: $where_like.=" asset.nns_pinyin like '{$search}%'";break;
		    	}
		    	
		    	$where_like .=' or';
			}
			$where_like=rtrim ($where_like,'or');
			$where_like.=") ";
		}
		$where_tag = '';
		if($tag!==NULL && $tag!==''){
			$where_tag = "and ((LOCATE(',{$tag},',CONCAT(',',asset.nns_tag)))>0 or asset.nns_tag='' or ISNULL(asset.nns_tag))";
		}
		
		$where_type = '';
		if($video_type!==NULL && $video_type!==''){
			$where_type = "and asset.nns_video_type='{$video_type}' ";
		}
		
    	$sql="select count(*) as sum from nns_assists_item as asset  where {$asset_sql} {$child_category} {$where_tag} {$where_like} {$where_type} {$except_sql}";
//		echo $sql;die;
    	$r=nl_query_by_db($sql, $dc->db());

    	return isset($r[0]['sum'])?$r[0]['sum']:0;
	}
	
	/**
	 * 根据第三方注入ID组获取视频信息列表
	 * @param dc DC模块
	 * @param array 第三方注入ID组
	 */
	static public function get_asset_list_by_import_ids($dc,$import_ids,$source=NULL){
		$import_ids_str='';
		if (!is_array($import_ids)) return TRUE;
		foreach ($import_ids as $import_id){
			$import_ids_str.='\''.$import_id.'\',';
		}
		$import_ids_str=rtrim($import_ids_str,',');
		$sql = 'select ' .
				'b.nns_id as video_id,b.nns_asset_import_id,a.* ' .
				'from nns_assists_item as a ' .
				'left join nns_vod as b ' .
				'on b.nns_id=a.nns_video_id ' .
				'where b.nns_asset_import_id in ('.$import_ids_str.') ' ;
				
		if (!empty($source)){
			$sql.='and b.nns_import_source=\''.$source.'\'';
		}
		
		$assets=nl_query_by_db($sql, $dc->db());
		
		if (!is_array($assets)) return $assets;
		
		$assets=np_array_rekey($assets,'nns_asset_import_id');
		
		$result=array();
		
		foreach ($import_ids as $import_id){
			if ($assets[$import_id]){
				array_push($result,$assets[$import_id]);
			}
		}
		
		return $result;
	}
    
        /**
         * LMS 13.7.18
         * @param type $dc
         * @param type $param
         * @param type $search_type
         * @param type $page_size
         * @param type $page_no
         * @param type $order
         * 搜索的字段和获取的字段以VOD表为准
         */
        static public function serrch_asset_item_list($dc, $param, $search_type = 0, $field = '*', $page_no = 0, $page_size = 10, $order = 0) {
                $search_type = $search_type != 1 ? 'OR' : 'AND';
                switch ($order) {
                        case 1:
                                $order_str = 'nns_play_count desc '; //播放次数排序
                                break;
                        case 2:
                                $order_str = 'nns_video_name asc ';  //节目名称排序
                                break;
                        case 3:
                                $order_str = 'nns_pinyin asc '; //首字母排序 0-7 a-z
                                break;
                        default:
                                $order_str = 'nns_order desc ';
                                break;
                }
                $where = '';

                foreach ($param as $f => $val) {

                        $where .= end($param) == $val ? " vi.nns_$f like '$val'" : " vi.nns_$f like '$val' $search_type "; //如果是最后一个 则不加 OR AND
                }

                $field = $field == 'count' ? 'count(*) as count' : $field;
                $sql = "SELECT $field FROM `nns_assists_item` as ai, `nns_vod` as vi WHERE ai.nns_video_id = vi.nns_id AND ({$where}) ORDER BY ai.$order_str LIMIT $page_no, $page_size";
                $result = nl_query_by_db($sql, $dc->db());
                return $result;
        }
}

//include_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'nl_common.func.php';
//$dc=nl_get_dc(array("db_policy"=>NL_DB_WRITE,"cache_policy"=>NP_KV_CACHE_TYPE_MEMCACHE));
//$dc->open();
//$r=nl_asset_item::get_asset_item_list_by_child($dc, "movie", 1000001, "0");
//echo '<pre>';
//print_r($r);
?>